#include <string.h>
#include "gkt_window.h"
#include "widget_draw.h"

#if defined(GKT_CONFIG_SCREEN_ENABLE) && GKT_CONFIG_SCREEN_ENABLE

#if (GKT_SCREEN_PF != GKT_SCREEN_PF_MONOCHROME)
#define WIDGET_LABEL_TITLE_MARK	0
#elif !defined(GKT_CONFIG_WIDGET_TITLE_MARK) || GKT_CONFIG_WIDGET_TITLE_MARK
#define WIDGET_LABEL_TITLE_MARK	1
#define WIDGET_LABEL_TITLE_MARK_PREFIX_CHAR	'*'
#define WIDGET_LABEL_TITLE_MARK_SUFFIX_CHAR	'*'
#define WIDGET_LABEL_TITLE_MARK_TEXT_MAXSIZE	\
	((GKT_SCREEN_WIDTH / GKT_WIDGET_FONT_MINSIZE) * 2)
#else
#define WIDGET_LABEL_TITLE_MARK	0
#endif

static int widget_label_paint(gkt_widget_s *widget, 
				uint32_t update)
{
#if WIDGET_LABEL_TITLE_MARK
	char full_text[WIDGET_LABEL_TITLE_MARK_TEXT_MAXSIZE + 1];
#endif
	uint32_t text_id;
	const char *text;

	text_id = widget->private_data ? widget->private_data : widget->desc->attr;
	text = GKT_TEXT(text_id);

#if WIDGET_LABEL_TITLE_MARK
	if (text && (widget->flags & GKT_WIDGET_F_TITLE_MARK)) {
		uint32_t text_len = strlen(text);
		uint32_t offset;

		if ((text_len + 4) <= WIDGET_LABEL_TITLE_MARK_TEXT_MAXSIZE) {
			full_text[0] = WIDGET_LABEL_TITLE_MARK_PREFIX_CHAR;
			full_text[1] = ' ';
			offset = 2;

			memcpy(&full_text[offset], text, text_len);
			offset += text_len;

			full_text[offset++] = ' ';
			full_text[offset++] = WIDGET_LABEL_TITLE_MARK_SUFFIX_CHAR;
			full_text[offset] = '\0';

			text = &full_text[0];
		}
	}
#endif

	widget_draw_background(widget, NULL, 0, 0);
	if (widget->flags & GKT_WIDGET_F_BORDER)
		widget_draw_border(widget, 0);
	if (__LIKELY(text))
		widget_draw_text(widget, NULL, text, ~0, 0, 0);
	if (update)
		widget_draw_update(widget);

	return GKT_SUCCESS;
}

int gkt_widget_label_event_handler(gkt_widget_s *widget, 
					uint32_t major_type, uint32_t minor_type, 
					uint32_t data)
{
	int retval = GKT_EVENT_HANDLE_CONTINUE;

	if (GKT_EVENT_WIDGET == major_type) {
		retval = GKT_EVENT_HANDLE_COMPLETE;

		if (GKT_WIDGET_EVENT_SHOW == minor_type)
			widget_label_paint(widget, data);
		else if (GKT_WIDGET_EVENT_HIDE == minor_type) {
			if (data & GKT_WIDGET_PAINT_EXCUTE) {
				widget_draw_clear(widget, 
					data & GKT_WIDGET_PAINT_UPDATE ? 1 : 0);
			}
		}
		else if (GKT_WIDGET_EVENT_SET_DATA == minor_type) {
			widget->private_data = data;
			if (widget->flags & GKT_WIDGET_F_SHOW)
				widget_label_paint(widget, 1);
		}
	}

	return retval;
}

#endif

